import {getFunctions,updateFunctions,deleteFunctions,exportFunctions} from "./api";
import {storage} from "../utils/storage";
import {message} from "ant-design-vue";
/**
 * get functions from local files
 *
 * @params force whether get functions hard
 *
 * if storage has keyMap,no longer get functions from files,unless with force
 *
 * index.js and package.json are excluded
 */
export async function getLocalFunctions(force){
    if(!force && storage.local.get('keyMap')){
        return 'false'
    }
    let files = await getFunctions()
    files = files.filter(item=>{
        if(item.file.includes('package.json') || item.file.includes('index.js')){
            return false
        }
        return  true
    })
    await setStorageFromFile(files)
    return true
}
/**
 * update functions in local files
 */
export async function updateLocalFunctions(functionObj){
    const res = await updateFunctions(functionObj)
    if(res.type === 'success'){
        message.success('本地文件更新成功，查看' + res.msg)
    }
}
/**
 * delete functions of files
 */
export async function deleteLocalFunctions(key){
    await deleteFunctions({key})
}
/**
 * export functions by files
 */
export async function exportESMFunctions({codes,name}){
    const res = await exportFunctions({codes,name})
    return res
}
/**
 * save functions to storage according to files
 *
 * item is split by //**-// (no -)
 * key and value are split by :
 */
function setStorageFromFile(files){
    storage.local.removeAll();
    let keyMap = []
    let nameMap = []
    const promise = files.map(file=>{
        return new Promise(resolve => {
            let funcInfo = {}
            const infos = file.content.split('//**//');
            let doc = {}
            infos.forEach(info=>{
                const infoArray = info.split('::')
                if(infoArray.length>=2){
                    const name = infoArray[0].trim()
                    let value = infoArray[1].trim()
                    try {
                        console.log(JSON.parse(value))
                        doc[name] = JSON.parse(value)
                    }catch (e) {
                    }
                     funcInfo[name] = value
                }
            })
            funcInfo.doc = doc
            console.log(funcInfo,'funcInfo')
            keyMap.push(funcInfo.key)
            nameMap.push(funcInfo.name)
            storage.local.set(funcInfo.key,funcInfo,false)
            resolve()
        })
    })
    return Promise.all(promise).then(()=>{
        storage.local.set('keyMap',keyMap)
        storage.local.set('nameMap',nameMap)
        return
    })
}
